package cn.myjerry.others.guava;

import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.List;
import java.util.Set;

import com.google.common.base.Function;
import com.google.common.base.Functions;
import com.google.common.base.Predicate;
import com.google.common.collect.Collections2;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;

/**
 * 函数试编程 1、Predicate 2、Function
 * 
 * 工具： 
 * Collections2.filter() 过滤器
 * Collections2.transform() 类型转换
 * Functions.compose() 组合试函数编程
 * @author Jerry
 *
 */
public class Demo02 {
	public static void main(String[] args) {
		// 组合式函数编程
		// 确保容器中的字符串长度不超过5，超过截取，并全部大写
		List<String> list = Lists.newArrayList("myjerry","zpon","aixingouapp");
		// 确保容器中的字符串长度不超过5，超过截取
		Function<String, String> f1 = new Function<String, String>() {
			@Override
			public String apply(String input) {
				return input.length() > 5 ? input.substring(0, 5) : input;
			}
		};
		// 并全部大写
		Function<String, String> f2 = new Function<String, String>() {
			@Override
			public String apply(String input) {
				return input.toUpperCase();
			}
		};
		// String => f2(f1(String))
		Function<String, String> f = Functions.compose(f1, f2);
		Collection<String> resultCol = Collections2.transform(list, f);
		for(String str:resultCol) {
			System.out.println(str);
		}
	}
	
	/**
	 * 类型转换
	 */
	public static void test02() {
		Set<Long> timeSet = Sets.newHashSet();
		timeSet.add(1000000000L);
		timeSet.add(99999999999999L);
		timeSet.add(333333333333L);
		Collection<String> timeStrCol = Collections2.transform(timeSet, new Function<Long, String>() {
			@Override
			public String apply(Long input) {
				return new SimpleDateFormat("yyyy-MM-dd").format(input);
			}
		});
		for (String time : timeStrCol) {
			System.out.println(time);
		}
	}

	/**
	 * 过滤器
	 */
	public static void test01() {
		List<String> list = Lists.newArrayList("moom", "def", "dad", "refer");
		// 找出回文(正着读跟倒着读是一样的) backwords mirrir words
		Collection<String> palindromelist = Collections2.filter(list, new Predicate<String>() {
			@Override
			public boolean apply(String input) {
				// 业务逻辑
				return new StringBuffer(input).reverse().toString().equals(input);
			}
		});
		for (String str : palindromelist) {
			System.out.println(str);
		}
	}
}
